﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;

namespace PDX.Validation
{
    /// <summary>
    /// Attaches a <see cref="ValidationModel"/> to the
    /// <see cref="PropertyModelAspectCollection"/> and keeps it up to date.
    /// </summary>
    public class ValidationManager
    {
        /// <summary>
        /// Gets the target.
        /// </summary>
        protected Context Target { get; private set; }

        /// <summary>
        /// Gets the adapter.
        /// </summary>
        protected IValidationAdapter Adapter { get; private set; }

        /// <summary>
        /// Gets the validation model.
        /// </summary>
        protected ValidationModel ValidationModel { get; private set; }

        /// <summary>
        /// Gets the notifier.
        /// </summary>
        protected Notification.INotificationManager Notifier { get; private set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="ValidationManager"/> class.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="adapter">The adapter.</param>
        /// <param name="notifier">The notifier.</param>
        public ValidationManager(Context context, IValidationAdapter adapter,
            Notification.INotificationManager notifier)
        {
            this.Target = context;
            this.Adapter = adapter;
            this.ValidationModel = new ValidationModel();
            this.Notifier = notifier;

            context.Loaded += (s, e) => Update();
            notifier.NotificationRaised += (s, e) => Update();
        }

        /// <summary>
        /// Updates the <see cref="ValidationModel"/> attached to the
        /// <see cref="IPropertyModel"/> of the <see cref="Target"/>.
        /// </summary>
        protected void Update()
        {
            var propModel = Context.GetPropertyModel(Target) as IPropertyModel;
            if (propModel != null)
            {
                var message = Adapter.GetMessage(Target);
                ValidationModel.Message = message;
                propModel.Ext["Validation"] = ValidationModel;
            }
        }
    }
}
